import { ckeckAllCart, deleteCart, findCart, getNewCartGoods, insertCart, mergeCart, updateCart } from '@/api/cart'

export default {
  namespaced: true,
  state () {
    return {
      // 购物车商品列表
      list: []
    }
  },
  getters: {
    // 有效商品列表
    validList (state) {
      return state.list.filter(goods => goods.stock > 0 && goods.isEffective)
    },
    // 有效商品总数和
    validTotal (state, getters) { // 同组件getters是第二个参数
      return getters.validList.reduce((p, c) => p + c.count, 0)
    },
    // 有效商品总价和
    validAmount (state, getters) {
      return getters.validList.reduce((p, c) => p + Math.round(c.nowPrice * 100) * c.count, 0) / 100
    },
    // 无效商品列表
    invalidList (state) {
      return state.list.filter(goods => goods.stock <= 0 || !goods.isEffective)
    },
    // 已选商品列表
    selectedList (state, getters) {
      return getters.validList.filter(item => item.selected)
    },
    // 已选商品总数和
    selectedTotal (state, getters) { // 同组件getters是第二个参数
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },
    // 已选商品总价和
    selectedAmount (state, getters) {
      return getters.selectedList.reduce((p, c) => p + Math.round(c.nowPrice * 100) * c.count, 0) / 100
    },
    // 是否全选
    isCheckAll (state, getters) {
      return getters.validList.length === getters.selectedList.length && getters.validList.length !== 0
    }
  },
  mutations: {
    // 添加购物车
    insertCart (state, payload) {
      // 查找购物车是否有相同商品
      const sameIndex = state.list.findIndex(goods => goods.skuId === payload.skuId)
      if (sameIndex > -1) { // 有
        payload.count = state.list[sameIndex].count + 1 // 数量+1
        state.list.splice(sameIndex, 1) // 删除原商品
      }
      state.list.unshift(payload) // 添加商品
    },
    // 修改购物车商品属性
    updateCart (state, goods) {
      // 修改对象
      const updateGoods = state.list.find(item => item.skuId === goods.skuId)
      for (const key in goods) {
        if (goods[key] === undefined && goods[key] === null && goods[key] === '') return
        updateGoods[key] = goods[key]
      }
    },
    // 删除购物车商品
    deleteCart (state, skuId) {
      const index = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(index, 1)
    },
    // 设置购物车
    setCart (state, payload) {
      state.list = payload
    }
  },
  actions: {
    // 添加购物车 传入商品对象
    insertCart (ctx, payload) {
      return new Promise((resolve) => {
        if (ctx.rootState.user.profile.token) { // 在store中得到其他store模块数据的方法
          // 已登录
          insertCart({ skuId: payload.skuId, count: payload.count }).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.commit('insertCart', payload)
          resolve() // promise构造函数在最后一定要使用resolve()来作为结束标识
        }
      })
    },
    // 更新购物车
    findCart (ctx) {
      return new Promise((resolve) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录
          findCart().then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          const PromiseArr = ctx.state.list.map(goods => { // 得到异步的商品属性对象组成的数组
            return getNewCartGoods(goods.skuId)
          })
          Promise.all(PromiseArr).then(dataList => { // 得到商品属性对象组成的数组
            dataList.forEach((data, i) => {
              // 把结果里的商品属性同步给购物车
              ctx.commit('updateCart', { skuId: ctx.state.list[i].skuId, ...data.result })
            })
            resolve()
          })
        }
      })
    },
    // 修改购物车商品属性 传入对象包含skuId和要修改的属性
    updateCart (ctx, payload) {
      return new Promise((resolve) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录
          updateCart(payload).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.commit('updateCart', payload)
          resolve()
        }
      })
    },
    // 删除购物车 传入skuId
    deleteCart (ctx, payload) {
      return new Promise((resolve) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录
          deleteCart([payload]).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.commit('deleteCart', payload)
          resolve()
        }
      })
    },
    // 全选和取消全选 传入布尔值
    checkAllCart (ctx, selected) {
      return new Promise((resolve) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录
          const ids = ctx.getters.validList.map(item => item.skuId)
          ckeckAllCart({ selected, ids }).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.getters.validList.forEach(goods => {
            ctx.commit('updateCart', { skuId: goods.skuId, selected })
          })
          resolve()
        }
      })
    },
    // 批量删除 传入布尔值，true清除失效商品，false清除选中商品
    batchDeleteCart (ctx, isClear) {
      return new Promise((resolve) => {
        if (ctx.rootState.user.profile.token) {
          // 已登录
          const ids = ctx.getters[isClear ? 'invalidList' : 'selectedList'].map(item => item.skuId)
          deleteCart(ids).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.getters[isClear ? 'invalidList' : 'selectedList'].forEach(goods => {
            ctx.commit('deleteCart', goods.skuId)
          })
          resolve()
        }
      })
    },
    // 修改购物车商品规格 传入对象包含旧skuId和新商品对象
    updateCartSku (ctx, { oldSkuId, newSku }) {
      return new Promise((resolve) => {
        const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
        if (ctx.rootState.user.profile.token) {
          // 已登录
          deleteCart([oldGoods.skuId]).then(() => {
            return insertCart({ skuId: newSku.skuId, count: oldGoods.count })
          }).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.commit('deleteCart', oldSkuId)
          const { skuId, price: nowPrice, specsText: attrsText, inventory: stock } = newSku
          const newGoods = { ...oldGoods, skuId, nowPrice, attrsText, stock }
          ctx.commit('insertCart', newGoods)
          resolve()
        }
      })
    },
    // 登录合并购物车
    async mergeCart (ctx) {
      const cartList = ctx.state.list.map(goods => {
        return { skuId: goods.skuId, selected: goods.selected, count: goods.count }
      })
      await mergeCart(cartList)
      // 清空
      ctx.commit('setCart', [])
    }
  }
}
